import FormPrintLodopApi from "@/api/form/core/formPrintLodop";
import FormWordTemplateApi from "@/api/form/core/formWordTemplate";
import FormPdfHtml from "@/views/modules/form/core/FormPdfHtml";
import {Util,PdfDialog,PrintQrCode,I18Parse,CommonLang} from "@lowcode/jpaas-common-lib";
import html2Canvas from "html2canvas";
import JsPDF from "jspdf";

import formbaseApi from '../../locales/lang/impl/form/formbaseApiLang';
import FormExcelTemplateApi from "@/api/form/core/formExcelTemplate";
import {exportExcel}  from '@/api/formbase/ExcelExport.js';


let lang = formbaseApi;
let i18n=function (langKey,text) {
    return I18Parse.getI18Val(lang.formbaseApi,langKey, text)
}

export default {
    data() {
        return {
            btnPrint: "",
            printArea: "",
            lodopUtil:{},
            timeOut:''
        }
    },
    methods: {
        initPrint(btnPrintId, printArea) {
            this.btnPrint = btnPrintId;
            this.printArea = printArea;
            var self_ = this;
            document.getElementById(this.btnPrint).addEventListener("click", function () {
                self_.print();
            })
        },
        print() {
            var self_ = this;
            var bodyHtml = window.document.body.innerHTML;
            var printHtml = this.$refs[this.printArea].innerHTML;
            window.document.body.innerHTML = printHtml;

            setTimeout(function () {
                window.print();
                window.document.body.innerHTML = bodyHtml;
                document.getElementById(self_.btnPrint).addEventListener("click", function () {
                    self_.print();
                })
            }, 2000);
        },
        printLodop(pkId, boAlias, name) {
            if (!pkId) {
                alert(i18n('msa.printLodopTips','未绑定套打模板!'));
                return;
            }
            var files = require.context('@/utils', true, /\.js$/);
            files.keys().forEach(key => {
                if (key.indexOf('/LodopFuncs.js') != -1) {
                    this.lodopUtil = files(key).default || files(key)
                }
            })
            var self=this;
            this.lodopUtil.onload(function(LODOP){
                if (!LODOP) {
                    return;
                }
                //初始化任务名称
                LODOP.PRINT_INIT(name);
                FormPrintLodopApi.printHtml({
                    pkId: pkId,
                    formData: JSON.stringify(self.rxForms.getData()[boAlias])
                }).then(res => {
                    eval(res.data);
                    //打印预览
                    LODOP.PREVIEW();
                })
            })
        },
        pdfPrint(pkId, boAlias, name) {
            var dataJson = this.rxForms.getData()[boAlias];
            var metadata = this.rxForms.getMetadata()[boAlias];
            //打开pdf模板
            var self = this;
            var conf = {
                component: FormPdfHtml,
                title: name + i18n('pdfTemplate','pdf模板'),
                widthHeight: [`100%`, `100%`]
            }
            var baseConf = {
                curVm: self,
                data: {   //传递参数
                    pkId: pkId,
                    dataJson: dataJson,
                    metadata: metadata
                }
            }
            let config = Object.assign(baseConf, conf)
            Util.open(config, function (action) {
            })
        },
        //Word打印
        wordPrint(btn) {
            let rxForms=this.parentVm.$refs.rxForms;
            btn.loading = true;
            var self = this;
            var formData=self.getRxFormData();
            var boDefId= btn.config.boDefId;
            var formName=self.formSolution? self.formSolution.name : rxForms.localData[0].title;
            var templateId=btn.config.templateId;
            if(!btn.config.templateId){
                self.$notification['warning']({message: I18Parse.getI18Val(CommonLang,'rxMsa.actionTips','操作提示'), description:i18n('msa.wordPrintTips','未绑定word模板!'),});
                return;
            }
            this.$confirm({
                content: i18n('msa.wordPrintConfirm','您确定要将当前表单打印成Word吗?'),
                zIndex: 40000,
                okText: I18Parse.getI18Val(CommonLang,'rxForm.ackBtn','确认'),
                cancelText: I18Parse.getI18Val(CommonLang,'rxForm.cancelBtn','取消'),
                onOk() {
                    //打印当前word 表单别名与表单数据
                    FormWordTemplateApi.wordPrint({boDefId:boDefId,formData:JSON.stringify(formData),single:true,templateId:templateId}).then(res=>{
                        if(!res){
                            self.$notification['error']({
                                message: I18Parse.getI18Val(CommonLang,'rxMsa.actionTips','操作提示'),
                                description:i18n('msa.wordPrintError','生成Word失败!'),
                            });
                            btn.loading = false;
                            return;
                        }
                        let blob = new Blob([res], {
                            type: 'application/vnd.ms-word'
                        });
                        let fileName = formName + '.docx';
                        if (window.navigator.msSaveOrOpenBlob) {
                            navigator.msSaveBlob(blob, fileName);
                        } else {
                            var link = document.createElement('a');
                            link.href = window.URL.createObjectURL(blob);
                            link.download = fileName;
                            link.click();
                            //释放内存
                            window.URL.revokeObjectURL(link.href)
                        }
                        btn.loading = false;
                    });
                },
                onCancel() {
                    btn.loading = false;
                }
            });
        },
        pdfDownload(btn) {
            var rxForms=this.parentVm.$refs.rxForms
            if (!rxForms){
                rxForms=this.parentVm.$refs.rxForm;
            }
            btn.loading = true;
            var self = this;
            var formData=self.getRxFormData();
            var boDefId= btn.config.boDefId;
            var formName=self.formSolution? self.formSolution.name : rxForms.localData[0].title;
            var templateId=btn.config.templateId;
            if(!btn.config.templateId){
                self.$notification['warning']({message: self.$ti18('rxMsa.actionTips','操作提示'), description:i18n('msa.wordPrintTips','未绑定word模板!'),});
                return;
            }
            this.$confirm({
                content: i18n('msa.pdfDownConfirm','您确定要下载PDF文档吗?'),
                zIndex: 40000,
                okText: self.$ti18('rxForm.ackBtn','确认'),
                cancelText: self.$ti18('rxForm.cancelBtn','取消'),
                onOk() {
                    //打印当前word 表单别名与表单数据
                    FormWordTemplateApi.pdfPrint({boDefId:boDefId,formData:JSON.stringify(formData),single:true,templateId:templateId}).then(res=>{
                        if(!res){
                            self.$notification['error']({
                                message: self.$ti18('rxMsa.actionTips','操作提示'),
                                description:i18n('msa.pdfDownError','生成PDF失败!'),
                            });
                            btn.loading = false;
                            return;
                        }
                        let blob = new Blob([res], {
                            type: 'application/pdf'
                        });
                        let fileName = formName + '.pdf';
                        if (window.navigator.msSaveOrOpenBlob) {
                            navigator.msSaveBlob(blob, fileName);
                        } else {
                            var link = document.createElement('a');
                            link.href = window.URL.createObjectURL(blob);
                            link.download = fileName;
                            link.click();
                            //释放内存
                            window.URL.revokeObjectURL(link.href)
                        }
                        btn.loading = false;
                    });
                },
                onCancel() {
                    btn.loading = false;
                }
            });
        },
        openPdf(btn) {
            var rxForms=this.parentVm.$refs.rxForms
            if (!rxForms){
                rxForms=this.parentVm.$refs.rxForm;
            }
            var self = this;
            var formData=self.getRxFormData()
            var boDefId= btn.config.boDefId;
            var formName=self.formSolution? self.formSolution.name : rxForms.localData[0].title;
            var templateId=btn.config.templateId;
            if(!btn.config.templateId){
                self.$notification['warning']({message: self.$ti18('rxMsa.actionTips','操作提示'), description:i18n('msa.wordPrintTips','未绑定word模板!'),});
                return;
            }

            let params={boDefId:boDefId,formData:JSON.stringify(formData),single:true,templateId:templateId};

            var conf = {
                component: PdfDialog,
                curVm: this,
                max: true,
                title: i18n('openPdf','打开PDF'),
                data:{
                    params:params
                }
            };
            Util.open(conf)
        },
        printPdfImg(btn){
            let scale = 1;
            let self_=this;
            let dmoWidth = document.querySelector(".previewBox").offsetWidth;
            if(dmoWidth>595.28){
                scale = dmoWidth / 595.28 ;
            }
            html2Canvas(document.querySelector(".previewBox"), {
                allowTaint: true, // 开启跨域
                scale // 提升画面质量，但是会增加文件大小
            }).then(function(canvas) {
                const contentWidth = canvas.width / scale;
                const contentHeight = canvas.height / scale;
                let pageHeight = contentWidth / 592.28 * 841.89 ;  // 1762.58 canvas上每一页的高度
                //未生成pdf的html页面高度
                let leftHeight = contentHeight;
                var position = 0;
                var imgWidth = 595.28; // A4 宽度
                var imgHeight = 592.28/ contentWidth * contentHeight; // A4总高度
                const PDF = new JsPDF('', 'pt', 'a4');
                const pageData = canvas.toDataURL('image/jpeg', 1.0);
                if (leftHeight < pageHeight) {
                    PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight );
                } else {
                    while(leftHeight > 0) {
                        PDF.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
                        leftHeight -= pageHeight ;
                        position =(position + 10 ) - 841.89;
                        //避免添加空白页
                        if(leftHeight > 0) {
                            PDF.addPage();
                        }
                    }
                }
                //  PDF.addImage(pageData, 'JPEG', 0, 0, contentWidth, contentHeight);
                let url=PDF.output("bloburl");
                btn.loading=false;

                Util.open({
                    component: PrintQrCode,
                    curVm: self_,
                    max: true,
                    title: i18n('printPdf','打印PDF'),
                    data: {url: url}
                }, function (action) {
                });
            })
        },
        printPdf(btn){
            btn.loading=true;
            this.$message.warning(i18n('msa.printPdfTips','打印启动中...'));
            this.timeOut = setTimeout(()=>{
                this.printPdfImg(btn)
            },300)
        },
        getRxFormData(){
            var formType=this.parentVm.processConfig.formType;
            var formData={};
            if(formType=="online") {
                if(this.rxForms){
                    formData=this.rxForms.getData();
                }else{
                    let alias=this.rxForm.formVm?this.rxForm.formVm.alias:this.rxForm.alias
                    formData[alias]=this.rxForm.getData();
                }
            }else{
                formData=this.customForm.getData();
            }
            return formData;
        },
        //Excel打印
        excelPrint(btn) {
            let rxForms=this.parentVm.$refs.rxForms;
            btn.loading = true;
            var self = this;
            var formData=self.getRxFormData();
            var boDefId= btn.config.boDefId;
            var title=self.formSolution? self.formSolution.name : rxForms.localData[0].title;
            var templateId=btn.config.templateId;
            if(!btn.config.templateId){
                self.$notification['warning']({message: I18Parse.getI18Val(CommonLang,'rxMsa.actionTips','操作提示'),
                    description:i18n('msa.excelPrintTips','未绑定模板!'),});
                return;
            }
            this.$confirm({
                content: i18n('msa.excelPrintConfirm','您确定要将当前表单打印成excel吗?'),
                zIndex: 40000,
                okText: I18Parse.getI18Val(CommonLang,'rxForm.ackBtn','确认'),
                cancelText: I18Parse.getI18Val(CommonLang,'rxForm.cancelBtn','取消'),
                onOk() {
                    //打印当前excel 表单别名与表单数据
                    FormExcelTemplateApi.excelPrint({boDefId:boDefId,formData:JSON.stringify(formData),templateId:templateId}).then(res=>{
                        if(res && res.data){
                            btn.loading = false;
                            exportExcel(res.data,title);
                        }else {
                            self.$notification['error']({
                                message: I18Parse.getI18Val(CommonLang,'rxMsa.actionTips','操作提示'),
                                description:i18n('msa.printError','生成失败!'),
                            });
                            btn.loading = false;
                            return;
                        }
                    });
                },
                onCancel() {
                    btn.loading = false;
                }
            });
        },
        //Excel对话框 excelDialog
        excelDialog(btn) {
            var self = this;
            var boDefId= btn.config.boDefId;
            var templateId=btn.config.templateId;
            if(!btn.config.templateId){
                self.$notification['warning']({message: I18Parse.getI18Val(CommonLang,'rxMsa.actionTips','操作提示'),
                    description:i18n('msa.excelPrintTips','未绑定模板!'),});
                return;
            }
            let obj={ pkId:self.pkId,alias:self.alias ,boDefId:boDefId,templateId:templateId };
            let params= window.btoa(encodeURIComponent(JSON.stringify(obj)));
            let url = `/luckyExcel/preview?params=${params}`;
            window.open(url,"_blank");
        },
    },
    destroyed() {
        clearTimeout(this.timeOut)
    }
}